﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using _WebShared.Classes;
using Telerik.Web.UI;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.APP.App_UI.UserControls;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class ESS_Project : System.Web.UI.Page
    {
        //double sumBath = 0;
        Main main = new Main();
        FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
        BGM_MAS_Source.BGM_MAS_Source source = new BGM_MAS_Source.BGM_MAS_Source();
        BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup expgrp = new BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup();
        BGM_MAS_Expense.BGM_MAS_Expense exp = new BGM_MAS_Expense.BGM_MAS_Expense();
        BGM_MAS_Option.BGM_MAS_Option op = new BGM_MAS_Option.BGM_MAS_Option();
        BGM_StrategyDataMapping.BGM_StrategyDataMapping strat = new BGM_StrategyDataMapping.BGM_StrategyDataMapping();
        BGM_Project.BGM_Project rec = new BGM_Project.BGM_Project();
        BGM_ProjectExpense.BGM_ProjectExpense recexp = new BGM_ProjectExpense.BGM_ProjectExpense();
        BGM_ProjectOperation.BGM_ProjectOperation pj = new BGM_ProjectOperation.BGM_ProjectOperation();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense pjexp = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        BGM_ProjectOperationPerson.BGM_ProjectOperationPerson pjper = new BGM_ProjectOperationPerson.BGM_ProjectOperationPerson();
        FIM_MAS_Contacts.FIM_MAS_Contacts con = new FIM_MAS_Contacts.FIM_MAS_Contacts();
        //FIM_MAS_ContactPersons.FIM_MAS_ContactPersons per = new FIM_MAS_ContactPersons.FIM_MAS_ContactPersons();
        //FIM_MAS_Currencies.FIM_MAS_Currencies cur = new FIM_MAS_Currencies.FIM_MAS_Currencies();
        BGM_ProjectReport.BGM_ProjectReport pjrpt = new BGM_ProjectReport.BGM_ProjectReport();
        BGM_ProjectOperationReport.BGM_ProjectOperationReport oprpt = new BGM_ProjectOperationReport.BGM_ProjectOperationReport();

        protected void Page_Load(object sender, EventArgs e)
        {
            ////=============== Set Toolbar ================
            //Toolbar1.ParentPanelGrid = PanelGrid;
            //Toolbar1.ParentPanelEdit = PanelEdit;
            //Toolbar1.ParentCmdAddNew = new Toolbar.ParentAddNew(AddNew1);
            //Toolbar1.ParentCmdEdit = new Toolbar.ParentEdit(Edit1);
            //Toolbar1.ParentCmdInsert = new Toolbar.ParentInsert(Insert1);
            //Toolbar1.ParentCmdUpdate = new Toolbar.ParentUpdate(Update1);
            //Toolbar1.ParentCmdDelete = new Toolbar.ParentDelete(Delete1);
            ////============================================

            //DropDownList_Contact1.Child = DropDownList_ContactPerson1.GetComboBox();

            if (!IsPostBack)
            {
                //================= Test =================
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year;
                txtBgmYear.MaxValue = year + 1;
                //========================================
                AddNew();

                LoadDDLBgmReceiveSeq();
                LoadGrdBgmProjectPerson();
                DropDownList_Emp1.LoadControl(null, null, null, null, null);
                DropDownList_Contact1.LoadControl(null, null);
                //DropDownList_ContactPerson1.LoadControl(null, null, null);
            }

            SetBgmProjectExpenseSummary();
            SetBgmSubActSummary();
        }

        protected void LoadRepeater1()
        {
            string strBgmProjSeq = ddlBgmReceiveSeq.SelectedValue;

            if (strBgmProjSeq.Length == 0)
                strBgmProjSeq = "-1";

            IList<BGM_MAS_Option.M_BGM_MAS_Option> infoList = op.GetListFromBgmProjSeq("3", strBgmProjSeq);// HardCode
            Repeater1.DataSource = infoList;
            Repeater1.DataBind();
            Repeater2.DataSource = infoList;
            Repeater2.DataBind();
        }

        protected void LoadRepeater4()
        {
            string strBgmReceiveSeq = ddlBgmReceiveSeq.SelectedValue;
            string strBgmProjOperSeq = lblBgmProjectSeq.Text;

            IList<BGM_Project.M_BGM_Project> infoList = rec.GetBudget(strBgmReceiveSeq, null, strBgmProjOperSeq);
            Repeater4.DataSource = infoList;
            Repeater4.DataBind();

            lblBgmProjName.Text = infoList[0].bgm_proj_name;
        }

        protected void LoadDDLBgmReceiveSeq()
        {
            ddlBgmReceiveSeq.DataSource = rec.GetList(txtBgmYear.Text
                , null, null);//Session["UserInternalJobsiteSeq"].ToString()
            ddlBgmReceiveSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlBgmReceiveSeq);
            ddlBgmReceiveSeq.SelectedIndex = 0;
        }

        protected void LoadGrdBgmProjectExpense()
        {
            if (lblMode.Text == "AddNew")
            {
                ViewState["ProjectExpInfo"] = pjexp.GetProjectExpense(null, ddlBgmReceiveSeq.SelectedValue);
                grdBgmProjectExpense.DataSource = ViewState["ProjectExpInfo"];
            }
            else
            {
                ViewState["ProjectExpInfo"] = pjexp.GetProjectExpense(lblBgmProjectSeq.Text
                    , ddlBgmReceiveSeq.SelectedValue);
                grdBgmProjectExpense.DataSource = ViewState["ProjectExpInfo"];
            }

            GridGroupByExpression group1 = new GridGroupByExpression(grdBgmProjectExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name"));
            GridGroupByExpression group2 = new GridGroupByExpression(grdBgmProjectExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name"));

            grdBgmProjectExpense.MasterTableView.GroupByExpressions.Add(group1);
            grdBgmProjectExpense.MasterTableView.GroupByExpressions.Add(group2);
            grdBgmProjectExpense.DataBind();
        }

        protected void LoadGrdBgmProjectPerson()
        {
            string strBgmProjectSeq = "-1";

            if (lblMode.Text != "AddNew")
            {
                strBgmProjectSeq = lblBgmProjectSeq.Text;
            }

            ViewState["ProjectPerInfo"] = pjper.GetFull(strBgmProjectSeq);
            grdBgmProjectPerson.DataSource = ViewState["ProjectPerInfo"];
            grdBgmProjectPerson.DataBind();

            if (lblRecordStatusSeq.Text == "A" && lblMode.Text == "Edit")
            {
                grdBgmProjectPerson.Columns[7].Visible = false;
            }
            else
            {
                grdBgmProjectPerson.Columns[7].Visible = true;
            }
        }

        protected void LoadFinProjectExpense()
        {
            RepeaterBgmSource.DataSource = GetRepeaterBgmSourceData();
            RepeaterBgmSource.DataBind();

            for (int i = 0; i < RepeaterBgmSource.Items.Count; i++)
            {
                RepeaterItem item = RepeaterBgmSource.Items[i];
                Label lblBgmSourceSeq = (Label)item.FindControl("lblBgmSourceSeq");
                Repeater RepeaterBgmExpGrp = (Repeater)item.FindControl("RepeaterBgmExpGrp");
                RepeaterBgmExpGrp.DataSource = GetRepeaterBgmExpGrpData(lblBgmSourceSeq.Text);
                RepeaterBgmExpGrp.DataBind();

                for (int j = 0; j < RepeaterBgmExpGrp.Items.Count; j++)
                {
                    RepeaterItem item2 = RepeaterBgmExpGrp.Items[j];
                    Label lblBgmExpGrpSeq = (Label)item2.FindControl("lblBgmExpGrpSeq");
                    Repeater RepeaterBgmExp = (Repeater)item2.FindControl("RepeaterBgmExp");

                    RepeaterBgmExp.DataSource = GetRepeaterBgmExpData(lblBgmSourceSeq.Text
                        , lblBgmExpGrpSeq.Text);
                    RepeaterBgmExp.DataBind();
                }
            }
        }

        protected IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> GetRepeaterBgmSourceData()
        {
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> listInfo = new List<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense>();
            Nullable<double> dSumAmount = 0;
            string strOldBgmSourceSeq = "";
            string strBgmSourceSeq = "";
            string strOldBgmSourceName = "";
            string strBgmSourceName = "";
            int nLastIndex = 0;

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                GridDataItem item = grdBgmProjectExpense.Items[i];
                Nullable<double> dBathAmount = ((RadNumericTextBox)item["bath_amount"].FindControl("txtBathAmount")).Value;

                if (dBathAmount > 0)
                {
                    nLastIndex = i;
                    strBgmSourceSeq = main.WebString(item["m_bgm_projectexpense.bgm_source_seq"].Text);
                    strBgmSourceName = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name"].Text);

                    if (strOldBgmSourceSeq == strBgmSourceSeq || i == 0)
                    {
                        dSumAmount += dBathAmount;
                    }
                    else
                    {
                        dSumAmount = dBathAmount;

                        BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense Info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                        BGM_ProjectOperationExpense.M_BGM_ProjectExpense PjExpInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectExpense();
                        BGM_ProjectOperationExpense.M_BGM_MAS_Source SourceInfo = new BGM_ProjectOperationExpense.M_BGM_MAS_Source();

                        PjExpInfo.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
                        Info.amount = dSumAmount;

                        SourceInfo.bgm_source_name = strBgmSourceName;
                        PjExpInfo.m_bgm_mas_source = SourceInfo;
                        Info.m_bgm_projectexpense = PjExpInfo;
                        listInfo.Add(Info);
                    }

                    strOldBgmSourceSeq = strBgmSourceSeq;
                    strOldBgmSourceName = strBgmSourceName;
                }
            }

            return listInfo;
        }

        protected IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> GetRepeaterBgmExpGrpData(string strBgmSourceSeq)
        {
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> listInfo = new List<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense>();
            Nullable<double> dSumAmount = 0;
            string strOldBgmExpGrpSeq = "";
            string strOldBgmExpGrpName = "";
            string strBgmExpGrpSeq = "";
            string strBgmExpGrpName = "";
            int nLastIndex = 0;

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                GridDataItem item = grdBgmProjectExpense.Items[i];
                Nullable<double> dBathAmount = ((RadNumericTextBox)item["bath_amount"].FindControl("txtBathAmount")).Value;
                string strExpBgmSourceSeq = main.WebString(item["m_bgm_projectexpense.bgm_source_seq"].Text);

                if (dBathAmount > 0 && strExpBgmSourceSeq == strBgmSourceSeq)
                {
                    nLastIndex = i;
                    strBgmExpGrpSeq = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text);
                    strBgmExpGrpName = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name"].Text);

                    if (strOldBgmExpGrpSeq == strBgmExpGrpSeq || i == 0)
                    {
                        dSumAmount += dBathAmount;
                    }
                    else
                    {
                        dSumAmount = dBathAmount;
                        BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense Info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                        BGM_ProjectOperationExpense.M_BGM_ProjectExpense PjExpInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectExpense();
                        BGM_ProjectOperationExpense.M_BGM_MAS_Expense expInfo = new BGM_ProjectOperationExpense.M_BGM_MAS_Expense();

                        Info.amount = dSumAmount;

                        expInfo.bgm_exp_grp_seq = main.ConvertNullInt(strBgmExpGrpSeq);
                        expInfo.bgm_exp_grp_name = strBgmExpGrpName;
                        PjExpInfo.m_bgm_mas_expense = expInfo;
                        Info.m_bgm_projectexpense = PjExpInfo;
                        listInfo.Add(Info);
                    }

                    strOldBgmExpGrpSeq = strBgmExpGrpSeq;
                    strOldBgmExpGrpName = strBgmExpGrpName;
                }
            }

            return listInfo;
        }

        protected IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> GetRepeaterBgmExpData(string strBgmSourceSeq, string strBgmExpGrpSeq)
        {
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> listInfo = new List<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense>();
            string strBgmExpName = "";
            string strBgmExpSeq = "";

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                GridDataItem item = grdBgmProjectExpense.Items[i];
                Nullable<double> dBathAmount = ((RadNumericTextBox)item["bath_amount"].FindControl("txtBathAmount")).Value;
                string strExpBgmSourceSeq = main.WebString(item["m_bgm_projectexpense.bgm_source_seq"].Text);
                string strExpBgmExpGrpSeq = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text);

                if (dBathAmount > 0 && strExpBgmSourceSeq == strBgmSourceSeq && strExpBgmExpGrpSeq  == strBgmExpGrpSeq)
                {
                    strBgmExpSeq = main.WebString(item["m_bgm_projectexpense.bgm_exp_seq"].Text);
                    strBgmExpName = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name"].Text);

                    BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense Info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                    BGM_ProjectOperationExpense.M_BGM_ProjectExpense PjExpInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectExpense();
                    BGM_ProjectOperationExpense.M_BGM_MAS_Expense expInfo = new BGM_ProjectOperationExpense.M_BGM_MAS_Expense();

                    Info.amount = dBathAmount;

                    PjExpInfo.bgm_exp_seq = main.ConvertNullInt(strBgmExpSeq);
                    expInfo.bgm_exp_name = strBgmExpName;
                    PjExpInfo.m_bgm_mas_expense = expInfo;
                    Info.m_bgm_projectexpense = PjExpInfo;
                    listInfo.Add(Info);
                }
            }

            return listInfo;
        }

        protected void LoadFinProjectPerson()
        {
            RepeaterPerson.DataSource = ViewState["ProjectPerInfo"];
            RepeaterPerson.DataBind();
        }

        protected void LoadFinishData()
        {
            lblFinBgmProjectDate.Text = dpBgmProjectDate.GetStringValue();
            lblFinBgmYear.Text = txtBgmYear.Text;
            lblFinStartDate.Text = dpStartDate.GetStringValue();
            lblFinEndDate.Text = dpEndDate.GetStringValue();
            lblFinBgmProjectName.Text = txtBgmProjectName.Text;
            lblFinAttendCount.Text = txtAttendCount.Text;
            lblRecordStatusName.Text = "รอดำเนินการอยู่";

            BGM_Project.M_BGM_Project RecInfo = new BGM_Project.M_BGM_Project();
            RecInfo = rec.GetInfo(ddlBgmReceiveSeq.SelectedValue);
            lblFinBgmRecName.Text = RecInfo.bgm_proj_name;
            lblFinBgmSubActName.Text = RecInfo.m_bgm_subactivity.bgm_strat_list_name;
            lblFinBgmActName.Text = RecInfo.m_bgm_activity.bgm_strat_list_name;
            lblFinBgmOutputName.Text = RecInfo.m_bgm_output.bgm_strat_list_name;

            LoadFinProjectExpense();
            LoadFinProjectPerson();
        }

        //protected IList<FIM_MAS_Currencies.M_FIM_MAS_Currencies> LoadDDLCurrencySeq()
        //{
        //    return cur.GetList();
        //}

        protected void SetBgmProjectExpenseSummary()
        {
            double dAmount = 0;
            double dExchangeRate = 0;
            double dBathAmount = 0;
            double dSumBathAmount = 0;

            RadNumericTextBox txtAmount = null;
            RadNumericTextBox txtExchangeRate = null;
            RadNumericTextBox txtBathAmount = null;
            RadNumericTextBox txtFooterAmount = null;
            GridItem[] Footer = grdBgmProjectExpense.MasterTableView.GetItems(GridItemType.Footer);

            if (Footer.Length > 0)
            {
                txtFooterAmount = (RadNumericTextBox)Footer[0].FindControl("txtFooterAmount");
            }
            else
            {
                return;
            }

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                txtAmount = (RadNumericTextBox)grdBgmProjectExpense.Items[i]["amount"].FindControl("txtAmount");
                txtExchangeRate = (RadNumericTextBox)grdBgmProjectExpense.Items[i]["exchange_rate"].FindControl("txtExchangeRate");
                txtBathAmount = (RadNumericTextBox)grdBgmProjectExpense.Items[i]["bath_amount"].FindControl("txtBathAmount");

                if (txtAmount.Text.Length > 0)
                    dAmount = Convert.ToDouble(txtAmount.Text);
                else
                    dAmount = 0;

                if (txtExchangeRate.Text.Length > 0)
                    dExchangeRate = Convert.ToDouble(txtExchangeRate.Text);
                else
                    dExchangeRate = 0;

                dBathAmount = dAmount * dExchangeRate;
                txtBathAmount.Text = dBathAmount.ToString();
                dSumBathAmount += dBathAmount;
            }

            txtFooterAmount.Value = dSumBathAmount;
            //txtSumBathAmount.Value = dSumBathAmount;
        }

        protected void SetBgmSubActSummary()
        {
            double dAmount = 0;
            double dSumGrpAmount = 0;

            for (int i = 0; i < Repeater4.Items.Count; i++)
            {
                RadNumericTextBox txtGrpAmount = (RadNumericTextBox)Repeater4.Items[i].FindControl("txtGrpAmount");
                txtGrpAmount.Text = "0";
            }

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                string strBgmSourceSeq = grdBgmProjectExpense.Items[i]["m_bgm_projectexpense.bgm_source_seq"].Text;
                string strBgmExpGrpSeq = grdBgmProjectExpense.Items[i]["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text;
                RadNumericTextBox txtAmount = (RadNumericTextBox)grdBgmProjectExpense.Items[i]["amount"].FindControl("txtAmount");
                RadNumericTextBox txtGrpAmount = GetTextSumSubActAmount(strBgmSourceSeq, strBgmExpGrpSeq);

                if (txtAmount.Text.Length > 0)
                    dAmount = Convert.ToDouble(txtAmount.Text);
                else
                    dAmount = 0;

                if (txtGrpAmount.Text.Length > 0)
                    dSumGrpAmount = Convert.ToDouble(txtGrpAmount.Text);
                else
                    dSumGrpAmount = 0;

                txtGrpAmount.Text = (dSumGrpAmount + dAmount).ToString();
            }
        }

        protected void UpdateUI1(string strCommand)
        {
            switch (strCommand)
            {
                case "AddNew":
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;
                    cmdCancel1.Visible = false;
                    break;
                case "Edit":
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    cmdCancel1.Visible = true;
                    break;
            }
        }

        protected void ClearTab1()
        {
            dpBgmProjectDate.SetValue("");
            dpStartDate.SetValue("");
            dpEndDate.SetValue("");
            lblBgmProjectSeq.Text = "";
            txtBgmProjectName.Text = "";
            ddlBgmReceiveSeq.SelectedIndex = 0;
            txtAttendCount.Text = "";
            LoadRepeater1();
        }

        protected void ClearTab2()
        {
            grdBgmProjectExpense.DataSource = "";
            grdBgmProjectExpense.DataBind();
            Repeater4.DataSource = "";
            Repeater4.DataBind();
            SetBgmProjectExpenseSummary();
            SetBgmSubActSummary();
        }

        protected void ClearTab3()
        {
            grdBgmProjectPerson.DataSource = null;
            grdBgmProjectPerson.DataBind();
            ClearControl1();
        }

        protected void ClearTab4()
        {
            lblFinBgmProjectDate.Text = "";
            lblFinBgmRecName.Text = "";
            lblFinBgmSubActName.Text = "";
            lblFinBgmYear.Text = "";
            lblFinStartDate.Text = "";
        }

        protected void ClearControl1()
        {
            DropDownList_Contact1.SetSelectedValue("");
            //DropDownList_ContactPerson1.SetSelectedValue("");
            DropDownList_Emp1.SetSelectedValue("");
            lblEmpPosName.Text = "";
            lblJobsiteName.Text = "";
            lblClassName.Text = "";
        }

        protected void AddNew()
        {
            lblMode.Text = "AddNew";
            ClearTab1();
            ClearTab2();
            ClearTab3();
            ClearTab4();
            main.UpdateTabStrip(RadTabStrip1, 0, lblMode.Text);
            UpdateTabPanel(0);
            dpBgmProjectDate.SetValue(DateTime.Today.ToShortDateString());
            cmdAddNew.Visible = false;
        }

        protected void Edit(string strSeq)
        {
            Session["ReportSeq"] = strSeq;
            lblMode.Text = "Edit";
            BGM_ProjectOperation.M_BGM_ProjectOperation info = pj.GetInfo(strSeq);

            dpBgmProjectDate.SetValue(info.bgm_proj_oper_date);
            txtBgmYear.Text = info.bgm_year.ToString();
            lblBgmProjectSeq.Text = info.bgm_proj_oper_seq.ToString();
            ddlBgmReceiveSeq.SelectedValue = info.bgm_proj_seq.ToString();
            LoadRepeater1();
            LoadRepeater4();
            dpStartDate.SetValue(info.start_date);
            dpEndDate.SetValue(info.end_date);
            txtBgmProjectName.Text = info.bgm_proj_oper_name;
            txtAttendCount.Text = info.attend_count.ToString();
            lblRecordStatusSeq.Text = info.record_status;
            lblRecordStatusName.Text = info.record_status_name;

            LoadGrdBgmProjectExpense();
            LoadGrdBgmProjectPerson();
            LoadFinishData();
            RadTabStrip1.SelectedIndex = 3;
            RadTabStrip1_TabClick(null, null);
            cmdAddNew.Visible = true;
        }

        private bool CheckData1()
        {
            bool bOK = true;
            string strError = "";
            string strBgmProjectDate = dpBgmProjectDate.GetStringValue();
            string strBgmRecSeq = ddlBgmReceiveSeq.SelectedValue;
            string strBgmProjectName = txtBgmProjectName.Text;

            if (strBgmProjectDate.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [วันที่ทำรายการ] !!";
                imgBgmProjectDate.Visible = true;
            }
            else if (strBgmRecSeq.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [รายการงบประมาณ] !!";
                imgBgmRecSeq.Visible = true;
            }
            else if (strBgmProjectName.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [ชื่องาน] !!";
                imgBgmProjectName.Visible = true;
            }
            else
            {
                imgBgmProjectDate.Visible = false;
                imgBgmRecSeq.Visible = false;
                imgBgmProjectName.Visible = false;
            }

            lblError.Text = strError;
            return bOK;
        }

        private bool CheckData2()
        {
            bool bOK = true;
            string strError = "";
            //double dBathAmount = txtSumBathAmount.Value.Value;

            //if (txtSumBathAmount.Text.Length == 0 || dBathAmount <= 0)
            //{
            //    bOK = false;
            //    strError = "กรุณากรอกข้อมูล [จำนวนเงินที่ขออนุมัติ] !!";
            //}
            //else 
                if (!CheckSubActAmount())
            {
                bOK = false;
                strError = "[จำนวนเงินที่ขออนุมัติ] เกินวงเงินที่คงเหลือในกิจกรรม !!";
            }

            lblError.Text = strError;
            return bOK;
        }

        private bool CheckData3()
        {
            bool bOK = true;
            string strError = "";

            if (grdBgmProjectPerson.Items.Count == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [คณะทำงาน] !!";
            }

            lblError.Text = strError;
            return bOK;
        }

        private bool CheckSubActAmount()
        {
            for (int i = 0; i < Repeater4.Items.Count; i++)
            {
                Label lblRemainAmount = (Label)Repeater4.Items[i].FindControl("lblRemainAmount");
                RadNumericTextBox txtGrpAmount = (RadNumericTextBox)Repeater4.Items[i].FindControl("txtGrpAmount");

                double dRemainAmount = (lblRemainAmount.Text.Length > 0 ? Convert.ToDouble(lblRemainAmount.Text) : 0);
                double dGrpAmount = (txtGrpAmount.Text.Length > 0 ? Convert.ToDouble(txtGrpAmount.Text) : 0);

                if (dRemainAmount < dGrpAmount)
                {
                    return false;
                }
            }

            return true;
        }

        protected RadNumericTextBox GetTextSumSubActAmount(string strBgmSourceSeq, string strBgmExpGrpSeq)
        {
            for (int i = 0; i < Repeater4.Items.Count; i++)
            {
                HtmlInputHidden hBgmSourceSeq = (HtmlInputHidden)Repeater4.Items[i].FindControl("hBgmSourceSeq");
                HtmlInputHidden hBgmExpGrpSeq = (HtmlInputHidden)Repeater4.Items[i].FindControl("hBgmExpGrpSeq");

                if (hBgmSourceSeq != null || hBgmExpGrpSeq != null)
                {
                    if (hBgmSourceSeq.Value == strBgmSourceSeq && hBgmExpGrpSeq.Value == strBgmExpGrpSeq)
                    {
                        RadNumericTextBox txtGrpAmount = (RadNumericTextBox)Repeater4.Items[i].FindControl("txtGrpAmount");

                        return txtGrpAmount;
                    }
                }
            }

            return null;
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            UpdateTabPanel(i);
            main.UpdateTabStrip(RadTabStrip1, i, lblMode.Text);
        }

        private void UpdateTabPanel(int i)
        {
            switch (i)
            {
                case 0:
                    PanelProject.Visible = true;
                    PanelExpense.Visible = false;
                    PanelPerson.Visible = false;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = false;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    cmdApprove.Visible = false;
                    break;
                case 1:
                    PanelProject.Visible = false;
                    PanelExpense.Visible = true;
                    PanelPerson.Visible = false;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    cmdApprove.Visible = false;
                    break;
                case 2:
                    PanelProject.Visible = false;
                    PanelExpense.Visible = false;
                    PanelPerson.Visible = true;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    cmdApprove.Visible = false;
                    break;
                case 3:
                    PanelProject.Visible = false;
                    PanelExpense.Visible = false;
                    PanelPerson.Visible = false;
                    PanelFinish.Visible = true;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = false;
                    cmdInsert.Visible = (lblMode.Text == "AddNew");
                    cmdUpdate.Visible = (lblMode.Text == "Edit");
                    cmdApprove.Visible = (lblMode.Text == "Edit");

                    bool bApprove = lblRecordStatusSeq.Text == "A";
                    cmdUpdate.Enabled = !bApprove;
                    cmdApprove.Enabled = !bApprove;

                    LoadFinishData();
                    break;
            }
        }

        protected void ddlBgmReceiveSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRepeater4();
            LoadGrdBgmProjectExpense();
            LoadRepeater1();
        }

        protected void rblType_SelectedIndexChanged(object sender, EventArgs e)
        {
            PanelEmployee.Visible = rblType.SelectedValue == "1";
            PanelContactPerson.Visible = rblType.SelectedValue == "2";
        }

        protected void grdBgmProjectExpense_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                RadNumericTextBox txtAmount = (RadNumericTextBox)dataItem["amount"].FindControl("txtAmount");
                RadNumericTextBox txtExchangeRate = (RadNumericTextBox)dataItem["exchange_rate"].FindControl("txtExchangeRate");
                RadNumericTextBox txtBathAmount = (RadNumericTextBox)dataItem["bath_amount"].FindControl("txtBathAmount");
                
                ImageButton cmdExpRate = (ImageButton)dataItem["amount"].FindControl("cmdExpRate");
                ImageButton cmdQty = (ImageButton)dataItem["amount"].FindControl("cmdQty");
                string strBgmExpSeq = main.WebString(dataItem["m_bgm_projectexpense.bgm_exp_seq"].Text);
                string strBgmSourceSeq = dataItem["m_bgm_projectexpense.bgm_source_seq"].Text;
                string strBgmExpGrpSeq = dataItem["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text;
                string strIcmResItemSeq = dataItem["icm_res_item_seq"].Text;
                int nExpRateCount = Convert.ToInt32(dataItem["exp_rate_count"].Text);
                RadNumericTextBox txtGrpAmount = GetTextSumSubActAmount(strBgmSourceSeq, strBgmExpGrpSeq);

                txtAmount.Attributes.Add("OnBlur", string.Format("txtBlur('{0}', '{1}', '{2}', '{3}')"
                    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID));
                txtAmount.Attributes.Add("OnFocus", string.Format("txtFocus('{0}', '{1}', '{2}', '{3}')"
                    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID));
                txtExchangeRate.Attributes.Add("OnBlur", string.Format("txtBlur('{0}', '{1}', '{2}', '{3}')"
                    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID));
                txtExchangeRate.Attributes.Add("OnFocus", string.Format("txtFocus('{0}', '{1}', '{2}', '{3}')"
                    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID));
                txtExchangeRate.Text = "1";
                txtAmount.Enabled = !(nExpRateCount > 0);
                cmdExpRate.Visible = nExpRateCount > 0;
                cmdQty.Visible = false;//main.WebString(strIcmResItemSeq).Length > 0;

                cmdExpRate.OnClientClick = string.Format("openWinExpRate('{0}', '{1}', '{2}', '{3}')"
                    , strBgmExpSeq, txtAmount.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID);
                cmdQty.OnClientClick = string.Format("openWinQty('{0}', '{1}', '{2}', '{3}')"
                    , strIcmResItemSeq, txtAmount.ClientID, txtBathAmount.ClientID
                    , txtGrpAmount.ClientID);

                if (txtBathAmount.Text.Length == 0)
                    txtBathAmount.Text = "0";

                if (txtGrpAmount.Text.Length == 0)
                    txtGrpAmount.Text = "0";
            }
        }

        protected void grdBgmProjectPerson_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> infoList = (IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson>)ViewState["ProjectPerInfo"];

            if (e.CommandName == "Delete")
            {
                string strProjectPerSeq = main.WebString(grdBgmProjectPerson.Items[e.Item.ItemIndex]["bgm_proj_oper_per_seq"].Text);

                if (strProjectPerSeq.Length > 0)
                {
                    BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();
                    info.bgm_proj_oper_per_seq = Convert.ToInt32(strProjectPerSeq);
                    info.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
                    info.updated_when = DateTime.Now;

                    pjper.Delete(info);
                }

                infoList.RemoveAt(e.Item.ItemIndex);

                grdBgmProjectPerson.DataSource = ViewState["ProjectPerInfo"];
                grdBgmProjectPerson.DataBind();
                ViewState["ProjectPerInfo"] = infoList;
            }
            else if (e.CommandName == "DataEdit")
            {
                BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info2 = infoList[e.Item.ItemIndex];
                lblIndex.Text = e.Item.ItemIndex.ToString();
                rblType.SelectedValue = (info2.emp_seq.ToString().Length > 0 ? "1" : "2");
                rblType_SelectedIndexChanged(null, null);

                if (rblType.SelectedValue == "1")
                {
                    DropDownList_Emp1.SetSelectedValue(info2.emp_seq.ToString());
                    lblEmpPosName.Text = info2.per_pos_name;
                    lblJobsiteName.Text = info2.per_job_site_name;
                    lblClassName.Text = info2.per_class_name;
                }
                else
                {
                    DropDownList_Contact1.SetSelectedValue(infoList[e.Item.ItemIndex].contact_seq.ToString());
                    //DropDownList_ContactPerson1.SetSelectedValue(infoList[e.Item.ItemIndex].contact_person_seq.ToString());
                }

                UpdateUI1("Edit");
                ViewState["ProjectPerInfo"] = infoList;
            }
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            if (DropDownList_Emp1.GetSelectedValue().Length > 0 || DropDownList_Contact1.GetSelectedValue().Length > 0)
            {
                string strBgmProjectSeq = lblBgmProjectSeq.Text;
                string strEmpSeq = null;
                string strContactSeq = null;
                //string strContactPersonSeq = null;
                string strPerName = null;
                string strPerPosName = null;
                string strPerClassName = null;
                string strPerJobsiteName = null;
                bool bFound = false;

                if (rblType.SelectedValue == "1")
                {
                    strEmpSeq = DropDownList_Emp1.GetSelectedValue();
                    strPerName = DropDownList_Emp1.GetComboBox().Text;
                    strPerJobsiteName = lblJobsiteName.Text;
                    strPerClassName = lblClassName.Text;
                    strPerPosName = lblEmpPosName.Text;

                    for (int i = 0; i < grdBgmProjectPerson.Items.Count; i++)
                    {
                        string strEmpSeqProject = main.WebString(grdBgmProjectPerson.Items[i]["emp_seq"].Text);
                        if (strEmpSeq == strEmpSeqProject)
                        {
                            bFound = true;
                        }
                    }
                }
                else
                {
                    strContactSeq = DropDownList_Contact1.GetSelectedValue();
                    //strContactPersonSeq = DropDownList_ContactPerson1.GetSelectedValue();
                    strPerName = DropDownList_Contact1.GetComboBox().Text;
                    strPerJobsiteName = "";// DropDownList_Contact1.GetComboBox().Text;

                    FIM_MAS_Contacts.M_FIM_MAS_Contacts ContactInfo = new FIM_MAS_Contacts.M_FIM_MAS_Contacts();
                    ContactInfo = con.GetInfo(strContactSeq);
                    strPerPosName = "";//ContactInfo.contact_person_position;

                    for (int i = 0; i < grdBgmProjectPerson.Items.Count; i++)
                    {
                        string strContactPersonProject = main.WebString(grdBgmProjectPerson.Items[i]["contact_seq"].Text);
                        if (strContactSeq == strContactPersonProject)
                        {
                            bFound = true;
                        }
                    }
                }

                if (bFound)
                {
                    lblError.Text = "มีรายการนี้แล้วในระบบแล้ว!!";
                }
                else
                {
                    BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();
                    info.emp_seq = main.ConvertNullInt(strEmpSeq);
                    info.contact_seq = main.ConvertNullInt(strContactSeq);
                    //info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
                    info.type_name = rblType.SelectedItem.Text;
                    info.per_name = strPerName;
                    info.per_pos_name = strPerPosName;
                    info.per_class_name = strPerClassName;
                    info.per_job_site_name = strPerJobsiteName;

                    ((IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson>)ViewState["ProjectPerInfo"]).Add(info);
                    grdBgmProjectPerson.DataSource = ViewState["ProjectPerInfo"];
                    grdBgmProjectPerson.DataBind();
                    UpdateUI1("AddNew");
                    ClearControl1();
                    lblError.Text = "";
                }                
            }
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            int nIndex = (lblIndex.Text.Length > 0 ? Convert.ToInt32(lblIndex.Text) : 0);
            string strBgmProjectSeq = lblBgmProjectSeq.Text;
            string strEmpSeq = null;
            string strContactSeq = null;
            //string strContactPersonSeq = null;
            string strTypeName = null;
            string strPerName = null;
            string strPerPosName = null;
            string strPerClassName = null;
            string strPerJobsiteName = null;
            IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> infoList = (IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson>)ViewState["ProjectPerInfo"];

            if (rblType.SelectedValue == "1")
            {
                strTypeName = "บุคคลภายใน";
                strEmpSeq = DropDownList_Emp1.GetSelectedValue();
                strPerName = DropDownList_Emp1.GetComboBox().Text;
                strPerPosName = lblEmpPosName.Text;
                strPerClassName = lblClassName.Text;
                strPerJobsiteName = lblJobsiteName.Text;
            }
            else
            {
                strTypeName = "บุคคลภายนอก";
                strContactSeq = DropDownList_Contact1.GetSelectedValue();
                //strContactPersonSeq = DropDownList_ContactPerson1.GetSelectedValue();
                strPerName = DropDownList_Contact1.GetComboBox().Text;
                strPerJobsiteName = "";// DropDownList_Contact1.GetComboBox().Text;
            }

            infoList[nIndex].emp_seq = main.ConvertNullInt(strEmpSeq);
            infoList[nIndex].contact_seq = main.ConvertNullInt(strContactSeq);
            //infoList[nIndex].contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            infoList[nIndex].type_name = strTypeName;
            infoList[nIndex].per_name = strPerName;
            infoList[nIndex].per_pos_name = strPerPosName;
            infoList[nIndex].per_class_name = strPerClassName;
            infoList[nIndex].per_job_site_name = strPerJobsiteName;

            grdBgmProjectPerson.DataSource = infoList;
            grdBgmProjectPerson.DataBind();
            UpdateUI1("AddNew");
            ClearControl1();
            ViewState["ProjectPerInfo"] = infoList;
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            UpdateUI1("AddNew");
            ClearControl1();
        }

        protected void cmdNext_Click(object sender, EventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            switch (i)
            {
                case 0 :
                    if (!CheckData1())
                        return;
                    break;
                case 1 :
                    if (!CheckData2())
                        return;
                    break;
                case 2 :
                    if (!CheckData3())
                        return;
                    break;
            }

            RadTabStrip1.SelectedIndex = i + 1;
            main.UpdateTabStrip(RadTabStrip1, i + 1, lblMode.Text);
            UpdateTabPanel(i + 1);
        }

        protected void cmdPrev_Click(object sender, EventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            RadTabStrip1.SelectedIndex = i - 1;
            main.UpdateTabStrip(RadTabStrip1, i - 1, lblMode.Text);
            UpdateTabPanel(i - 1);
        }

        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            //===================== Project ==========================
            string strBgmProjectSeq;
            string strBgmProjectDate = lblFinBgmProjectDate.Text;
            string strBgmProjectName = txtBgmProjectName.Text;
            string strStartDate = lblFinStartDate.Text;
            string strEndDate = lblFinEndDate.Text;
            string strAttendCount = lblFinAttendCount.Text;
            string strBgmYear = lblFinBgmYear.Text;
            string strBgmProjSeq = ddlBgmReceiveSeq.SelectedValue;
            //string strBgmOptionSeq = ddlBgmOptionSeq.SelectedValue;
            string strEmpSeq = Session["EmpSeq"].ToString();
            string strJobSiteSeq = Session["UserInternalJobsiteSeq"].ToString();
            string strIsUse = "1";
            string strUserID = Session["EmpSeq"].ToString();
            string strCurrencySeq = main.GetSystemControls().default_currency_seq.ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperation.M_BGM_ProjectOperation ProjectInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            
            ProjectInfo.bgm_proj_oper_date = main.ConvertNullDateTime(strBgmProjectDate);
            ProjectInfo.start_date = main.ConvertNullDateTime(strStartDate);
            ProjectInfo.bgm_proj_oper_name = strBgmProjectName;
            ProjectInfo.end_date = main.ConvertNullDateTime(strEndDate);
            ProjectInfo.bgm_year = main.ConvertNullInt(strBgmYear);
            ProjectInfo.bgm_proj_seq = main.ConvertNullInt(strBgmProjSeq);
            //ProjectInfo.bgm_option_seq = main.ConvertNullInt(strBgmOptionSeq);
            ProjectInfo.emp_seq = main.ConvertNullInt(strEmpSeq);
            ProjectInfo.job_site_seq = main.ConvertNullInt(strJobSiteSeq);
            ProjectInfo.is_use = strIsUse;
            ProjectInfo.attend_count = main.ConvertNullInt(strAttendCount); 

            ProjectInfo.created_by = main.ConvertNullInt(strUserID);
            ProjectInfo.created_when = dtNow;

            strBgmProjectSeq = pj.Insert(ProjectInfo);
            //pj.SelectRecentInsertedRoleSeq();
            //===================== Project Expense ==========================

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                if (((RadNumericTextBox)grdBgmProjectExpense.Items[i]["bath_amount"].FindControl("txtBathAmount")).Value > 0)
                {
                    BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense ExpenseInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                    //string strBgmSourceSeq = main.WebString(grdBgmProjectExpense.Items[i]["m_bgm_projectexpense.bgm_source_seq"].Text);
                    string strBgmProjExpSeq = main.WebString(grdBgmProjectExpense.Items[i]["bgm_proj_exp_seq"].Text);
                    
                    double dAmount = ((RadNumericTextBox)grdBgmProjectExpense.Items[i]["amount"].FindControl("txtAmount")).Value.Value;

                    ExpenseInfo.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjectSeq);
                    //ExpenseInfo.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
                    ExpenseInfo.bgm_proj_exp_seq = main.ConvertNullInt(strBgmProjExpSeq);
                    ExpenseInfo.amount = dAmount;
                    //ExpenseInfo.currency_seq = main.ConvertNullInt(strCurrencySeq);
                    //ExpenseInfo.exchange_rate = 1;
                    //ExpenseInfo.bath_amount = dAmount;

                    ExpenseInfo.created_by = main.ConvertNullInt(strUserID);
                    ExpenseInfo.created_when = dtNow;
                    pjexp.Insert(ExpenseInfo);
                }
            }
            //===================== Project Person ==========================
            for (int i = 0; i < grdBgmProjectPerson.Items.Count; i++)
            {
                BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson PersonInfo = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();
                string strPersonEmpSeq = main.WebString(grdBgmProjectPerson.Items[i]["emp_seq"].Text);
                string strContactSeq = main.WebString(grdBgmProjectPerson.Items[i]["contact_seq"].Text);
                string strContactPersonSeq = main.WebString(grdBgmProjectPerson.Items[i]["contact_person_seq"].Text);

                PersonInfo.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjectSeq);
                PersonInfo.emp_seq = main.ConvertNullInt(strPersonEmpSeq);
                PersonInfo.contact_seq = main.ConvertNullInt(strContactSeq);
                PersonInfo.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);

                PersonInfo.created_by = main.ConvertNullInt(strUserID);
                PersonInfo.created_when = dtNow;
                pjper.Insert(PersonInfo);
            }

            AddNew();
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            //===================== Project ==========================
            string strBgmProjectSeq = lblBgmProjectSeq.Text;
            string strBgmProjectDate = lblFinBgmProjectDate.Text;
            string strBgmProjectName = txtBgmProjectName.Text;
            string strStartDate = lblFinStartDate.Text;
            string strEndDate = lblFinEndDate.Text;
            string strAttendCount = lblFinAttendCount.Text;
            string strBgmYear = lblFinBgmYear.Text;
            string strBgmRecSeq = ddlBgmReceiveSeq.SelectedValue;
            //string strBgmOptionSeq = ddlBgmOptionSeq.SelectedValue;
            string strEmpSeq = Session["EmpSeq"].ToString();
            string strJobSiteSeq = Session["UserInternalJobsiteSeq"].ToString();
            string strIsUse = "1";
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperation.M_BGM_ProjectOperation ProjectInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();

            ProjectInfo.bgm_proj_oper_seq = Convert.ToInt32(strBgmProjectSeq);
            ProjectInfo.bgm_proj_oper_date = main.ConvertNullDateTime(strBgmProjectDate);
            ProjectInfo.bgm_proj_oper_name = strBgmProjectName;
            ProjectInfo.start_date = main.ConvertNullDateTime(strStartDate);
            ProjectInfo.end_date = main.ConvertNullDateTime(strEndDate);
            ProjectInfo.bgm_year = main.ConvertNullInt(strBgmYear);
            ProjectInfo.bgm_proj_seq = main.ConvertNullInt(strBgmRecSeq);
            //ProjectInfo.bgm_option_seq = main.ConvertNullInt(strBgmOptionSeq);
            ProjectInfo.emp_seq = main.ConvertNullInt(strEmpSeq);
            ProjectInfo.job_site_seq = main.ConvertNullInt(strJobSiteSeq);
            ProjectInfo.is_use = strIsUse;
            ProjectInfo.attend_count = main.ConvertNullInt(strAttendCount);

            ProjectInfo.updated_by = main.ConvertNullInt(strUserID);
            ProjectInfo.updated_when = dtNow;

            pj.Update(ProjectInfo);
            //===================== Project Expense ==========================

            for (int i = 0; i < grdBgmProjectExpense.Items.Count; i++)
            {
                //if (((RadNumericTextBox)grdBgmProjectExpense.Items[i]["bath_amount"].FindControl("txtBathAmount")).Value > 0)
                //{
                BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense ExpenseInfo = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
                string strBgmProjectExpSeq = main.WebString(grdBgmProjectExpense.Items[i]["bgm_proj_oper_exp_seq"].Text);
                //string strBgmSourceSeq = main.WebString(grdBgmProjectExpense.Items[i]["m_bgm_projectexpense.bgm_source_seq"].Text);
                string strBgmProjExpSeq = main.WebString(grdBgmProjectExpense.Items[i]["bgm_proj_exp_seq"].Text);
                string strCurrencySeq = main.GetSystemControls().default_currency_seq.ToString();

                ExpenseInfo.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjectSeq);
                //ExpenseInfo.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
                ExpenseInfo.bgm_proj_exp_seq = main.ConvertNullInt(strBgmProjExpSeq);
                ExpenseInfo.amount = ((RadNumericTextBox)grdBgmProjectExpense.Items[i]["amount"].FindControl("txtAmount")).Value;
                //ExpenseInfo.currency_seq = main.ConvertNullInt(strCurrencySeq);
                //ExpenseInfo.exchange_rate = 1;
                //ExpenseInfo.bath_amount = ((RadNumericTextBox)grdBgmProjectExpense.Items[i]["amount"].FindControl("txtAmount")).Value;

                if (strBgmProjectExpSeq == null || strBgmProjectExpSeq.Length == 0)
                {
                    if (ExpenseInfo.amount != null || ExpenseInfo.amount > 0)
                    {
                        ExpenseInfo.created_by = main.ConvertNullInt(strUserID);
                        ExpenseInfo.created_when = dtNow;
                        pjexp.Insert(ExpenseInfo);
                    }
                }
                else
                {
                    ExpenseInfo.bgm_proj_oper_exp_seq = main.ConvertNullInt(strBgmProjectExpSeq);
                    ExpenseInfo.updated_by = main.ConvertNullInt(strUserID);
                    ExpenseInfo.updated_when = dtNow;

                    if (ExpenseInfo.amount != null || ExpenseInfo.amount > 0)
                    {
                        pjexp.Update(ExpenseInfo);
                    }
                    else
                    {
                        pjexp.Delete(ExpenseInfo);
                    }
                }
                //}
            }
            //===================== Project Person ==========================
            for (int i = 0; i < grdBgmProjectPerson.Items.Count; i++)
            {
                BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson PersonInfo = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();
                string strBgmProjectPerSeq = main.WebString(grdBgmProjectPerson.Items[i]["bgm_proj_oper_per_seq"].Text);
                string strPersonEmpSeq = main.WebString(grdBgmProjectPerson.Items[i]["emp_seq"].Text);
                string strContactSeq = main.WebString(grdBgmProjectPerson.Items[i]["contact_seq"].Text);
                string strContactPersonSeq = main.WebString(grdBgmProjectPerson.Items[i]["contact_person_seq"].Text);

                PersonInfo.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjectSeq);
                PersonInfo.emp_seq = main.ConvertNullInt(strPersonEmpSeq);
                PersonInfo.contact_seq = main.ConvertNullInt(strContactSeq);
                PersonInfo.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);

                if (strBgmProjectPerSeq == null || strBgmProjectPerSeq.Length == 0)
                {
                    PersonInfo.created_by = main.ConvertNullInt(strUserID);
                    PersonInfo.created_when = dtNow;
                    pjper.Insert(PersonInfo);
                }
                else
                {
                    PersonInfo.bgm_proj_oper_per_seq = main.ConvertNullInt(strBgmProjectPerSeq);
                    PersonInfo.updated_by = main.ConvertNullInt(strUserID);
                    PersonInfo.updated_when = dtNow;
                    pjper.Update(PersonInfo);
                }
            }

            AddNew();
        }

        protected void cmdBgmReceiveHistory_Click(object sender, EventArgs e)
        {

        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            lblBgmProjectSeq.Text = e.Argument;
            Edit(e.Argument);
        }

        protected void cmdApprove_Click(object sender, EventArgs e)
        {
            string strBgmProjectSeq = lblBgmProjectSeq.Text;
            string strBgmProjectName = lblFinBgmProjectName.Text;
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperation.M_BGM_ProjectOperation ProjectInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> ExpInfo = pjexp.GetFull(strBgmProjectSeq, null, null);

            for (int i = 0; i < ExpInfo.Count; i++)
            {
                string strBgmProjExpSeq = ExpInfo[i].bgm_proj_exp_seq.ToString();
                string strBgmProjOperExpSeq = ExpInfo[i].bgm_proj_oper_exp_seq.ToString();
                string strBgmExpName = ExpInfo[i].m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name;
                double dAmount = ExpInfo[i].amount.Value;
                double dRemainAmount = pjrpt.GetCalculateList(null, strBgmProjExpSeq, null, null, null
                    , null, null, null, null, null, strBgmProjOperExpSeq)[0].cal_amount.Value;

                if (dAmount > dRemainAmount)
                {
                    lblError.Text = "จำนวนเงินคงเหลือของ [" + strBgmExpName + "] ไม่พออนุมัติ";
                    return;
                }

                BGM_ProjectReport.M_BGM_ProjectReport ProjRptInfo = new BGM_ProjectReport.M_BGM_ProjectReport();
                ProjRptInfo.descr = "" + " - " + strBgmProjectName;
                ProjRptInfo.bgm_proj_exp_seq = main.ConvertNullInt(strBgmProjExpSeq);
                ProjRptInfo.bgm_proj_oper_exp_seq = main.ConvertNullInt(strBgmProjOperExpSeq);
                ProjRptInfo.used_amount = dAmount;
                ProjRptInfo.cal_amount = -dAmount;
                ProjRptInfo.rpt_type = 4;
                ProjRptInfo.record_status = "W";
                ProjRptInfo.created_by = main.ConvertNullInt(strUserID);
                ProjRptInfo.created_when = dtNow;

                pjrpt.Insert(ProjRptInfo);

                BGM_ProjectOperationReport.M_BGM_ProjectOperationReport OperRptInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                OperRptInfo.descr = "" + " - " + strBgmProjectName;
                OperRptInfo.bgm_proj_oper_exp_seq = main.ConvertNullInt(strBgmProjOperExpSeq);
                OperRptInfo.used_amount = dAmount;
                OperRptInfo.cal_amount = dAmount;
                OperRptInfo.rpt_type = 1;
                OperRptInfo.record_status = "W";
                OperRptInfo.created_by = main.ConvertNullInt(strUserID);
                OperRptInfo.created_when = dtNow;

                oprpt.Insert(OperRptInfo);
            }

            ProjectInfo.bgm_proj_oper_seq = Convert.ToInt32(strBgmProjectSeq);
            ProjectInfo.record_status = "A";
            ProjectInfo.updated_by = main.ConvertNullInt(strUserID);
            ProjectInfo.updated_when = dtNow;

            pj.ChangeStatus(ProjectInfo);
            AddNew();
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            AddNew();
        }
    }
}
